package io.wdb.wx.activity.api;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import io.wdb.modules.activity.wx.dao.UserChannelInfoDao;
import io.wdb.modules.activity.wx.entity.UserChannelInfoEntity;
import io.wdb.wx.model.SNSUserInfo;
import io.wdb.wx.model.WeixinOauth2Token;
import io.wdb.wx.service.PrizeService;
import io.wdb.wx.util.AdvancedUtil;
import io.wdb.wx.util.WxConfigUtil;

@Controller
@RequestMapping("/wx")
public class RedirectPageController extends BaseController{
	private static final Logger logger = LoggerFactory.getLogger(RedirectPageController.class);

	@Resource(name="prizeServiceImpl")
	private PrizeService prizeService;
	
	@Resource(name="userChannelInfoDao")
	private UserChannelInfoDao userChannelInfoDao;
	
	@RequestMapping(value = "oauth")
	public Object getName(HttpServletRequest request, ModelMap map) {
		// 用户同意授权后，能获取到code
		String code = request.getParameter("code");
		// 用户同意授权
		SNSUserInfo snsUserInfo = new SNSUserInfo();
		UserChannelInfoEntity channelInfo = new UserChannelInfoEntity();
		if (!"authdeny".equals(code)) {
			// 获取网页授权access_token
			WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(appid, secret, code);
			// 网页授权接口访问凭证
			String accessToken = weixinOauth2Token.getAccessToken();
			// 用户标识
			String openId = weixinOauth2Token.getOpenId();
			// 获取用户信息
			snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
			channelInfo = userChannelInfoDao.selectByAccountId(snsUserInfo.getOpenId());
			if(channelInfo==null) {
				// TODO 用户信息初始化
				channelInfo=prizeService.initUserInfo(snsUserInfo.getOpenId(),snsUserInfo.getHeadImgUrl(),snsUserInfo.getNickname());
			}else {
				//用户信息和之前不一致
				if(!channelInfo.getChannelNickName().equals(snsUserInfo.getNickname())||!channelInfo.getChannelImg().equals(snsUserInfo.getHeadImgUrl())) {
					channelInfo.setChannelNickName(snsUserInfo.getNickname());
					channelInfo.setChannelImg(snsUserInfo.getHeadImgUrl());
					prizeService.updateUserInfo(channelInfo);
				}
			}
		}
		String redirectOther = request.getParameter("redirectOther");
		map.put("openid", snsUserInfo.getOpenId()==null?"":snsUserInfo.getOpenId());
		map.put("nickname", channelInfo.getChannelNickName());
		map.put("headimgurl", channelInfo.getChannelImg());
		map.put("user_id", channelInfo.getId());
		map.put("url", "https://"+redirectOther);
		logger.info("{}",map);
		return "oauth";
	}
	@RequestMapping(value = "/share", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> share(HttpServletRequest request) {
		logger.info("用户分享接口开始运行。。。。。。");
		try {
			String urlTemp = "http://" + request.getServerName() + request.getContextPath();
			String urlpath = "http://" + request.getServerName();
			String appUrl = request.getParameter("url");
			appUrl = appUrl.replaceAll("&amp;", "&");
			logger.info("初步获取到的url为:\t"+appUrl);
			if (request.getParameter("code") != null) {
				appUrl += "&code=" + request.getParameter("code");
			}
			if (request.getParameter("state") != null) {
				appUrl += "&state=" + request.getParameter("state");
			}
			if (request.getParameter("params") != null) {
				appUrl += request.getParameter("params");
			}
			logger.info("最终获取到的url为:\t"+appUrl);
			return WxConfigUtil.getSignature(appUrl, appid, secret, urlTemp, urlpath);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
    }
}
